package com.itheima.hanlder;

import com.itheima.exception.BusinessException;
import com.itheima.vo.Result;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//全局异常处理器
@RestControllerAdvice
public class GlobalExceptionHandler {

   @ExceptionHandler(Exception.class)
    public Result handlerException(Exception e){
       //1.打印异常信息
       e.printStackTrace();
       //2. 构造出现异常时的返回值
       return Result.error("服务器开小差了~");
   }

   @ExceptionHandler(DuplicateKeyException.class)
    public Result  handlerDuplicateKeyException(DuplicateKeyException e){
       //1. 打印异常信息
       e.printStackTrace();
       String message = e.getMessage();//2.进行异常处理
       if(message.contains("name") && message.contains("dept")){
           return Result.error("部门名称重复");
       }else if(message.contains("username") && message.contains("emp")){
           return Result.error("员工账号重复");
       }
       //3.构造出出现异常时的返回值
       return Result.error("输入参数名称重复!");
   }


   //自定义业务异常
    @ExceptionHandler(BusinessException.class)
    public Result handlerBusinessException(Exception e){
       //直接获取业务报错提示，返回给前端
        return Result.error(e.getMessage());
    }







}

